import glob from 'glob';
import { tools } from './tools/tools';

export { format_genrator };

namespace format_genrator {

    export interface FormatData {
        key: string,
        path: string,
        folderChildren: FormatData[],
        flieChildren: string[],
        relationArr:CLUDE_RELATION,
    }

    export interface CLUDE_RELATION {
        type:number,// 0：初始 1：*.* 或者*.*+exclude，2，有包含
        include: string[],
        exclude: string[],
    }

    export interface ReturnFormatData {
        include: string[],
        exclude: string[],
    }

    export class CfgFormat {

        /**
         * 
         * @param rootPath "E:/workspace/SSSS/resource/"
         * @param resArr includeArr
         * @returns 
         */
        public async resFormat(rootPath: string, resArr: string[]): Promise<ReturnFormatData> {
            // rootPath = "E:/workspace/SSSS/resource/";
            // let str = fs.readFileSync("E:/workspace/SSSS/resource_cfg/config.json", { encoding: "utf-8" });
            let tree = this.buildTree(resArr);
            await this.deepRecursionTraverse(rootPath, tree);
            
            let consoleObj: ReturnFormatData = { include: [], exclude: [] };
            for (let i = 0, length = tree.length; i < length; i++) {
                let child = tree[i];
                if (!child) {
                    continue;
                }
                consoleObj.include = consoleObj.include.concat(child.relationArr.include);
                consoleObj.exclude = consoleObj.exclude.concat(child.relationArr.exclude);
            }

            consoleObj.include.sort((a, b) => {
                return tools.HashNum(b) - tools.HashNum(a);
            });

            consoleObj.exclude.sort((a, b) => {
                return tools.HashNum(b) - tools.HashNum(a);
            });

            // console.log(consoleObj);
            // fs.writeFileSync("E:/work1/"+tree[0].key+"树.json", JSON.stringify(tree, null, 2), 'utf-8');
            return new Promise<ReturnFormatData>((resolve) => {
                resolve(consoleObj)
            });
        }

        public buildTree(resArr: string[]): FormatData[] {
            let tree: FormatData[] = [];
            for (let i = 0, length = resArr.length; i < length; i++) {
                let index = resArr[i].indexOf("/");
                let curFolderNode = tree;
                let curFildNode = [];
                if (index < 0) {
                    let newNode: FormatData = {
                        key: resArr[i], path: "",
                        folderChildren: [],
                        flieChildren: [resArr[i]],
                        relationArr: { type: 0, include: [], exclude: [] }
                    };
                    curFolderNode.push(newNode);
                    continue;
                }
                let pathSplitArr: string[] = resArr[i].split("/");
                let rootPath = "";
                for (let j = 0, length = pathSplitArr.length; j < length; j++) {
                    if (pathSplitArr[j] == "") {
                        break;
                    }
                    let wantedNode = pathSplitArr[j];
                    let index = -1;
                    for (let k = 0, length = curFolderNode.length; k < length; k++) {
                        if (curFolderNode[k].key == wantedNode) {
                            rootPath = curFolderNode[k].path;
                            curFildNode = curFolderNode[k].flieChildren;
                            curFolderNode = curFolderNode[k].folderChildren;
                            index = k;
                            break;
                        }
                    }
                    if (index >= 0) {
                        continue;
                    }
                    if (j == length - 1) {
                        curFildNode.push(rootPath += wantedNode);
                    } else {
                        rootPath += wantedNode + "/";
                        let newNode: FormatData = {
                            key: wantedNode, path: rootPath,
                            folderChildren: [],
                            flieChildren: [],
                            relationArr: { type: 0, include: [], exclude: [] }
                        };
                        curFolderNode.push(newNode);
                        curFolderNode = newNode.folderChildren;
                        curFildNode = newNode.flieChildren;
                    }
                }
            }
            return tree;
        }

        //遍历 包含关系
        private async deepRecursionTraverse(rootPath: string, data: FormatData[]) {
            if (!Array.isArray(data) || data.length <= 0) {
                return;
            }
            for (let i = 0, length = data.length; i < length; i++) {
                let item: FormatData = data[i];
                if (!item) {
                    continue;
                }
                await this.deepRecursionTraverse(rootPath, item.folderChildren);
                await this.doFile(rootPath, item);
                await this.doFolder(rootPath, item);
            }
            return;
        }

        private async doFile(rootPath: string, item: FormatData) {
            //子文件 处理
            let flieChildren = item.flieChildren;
            let realFileChildren = await this.getPathFile(item.path, "**.*", { nodir: true, cwd: rootPath });
            let fl = flieChildren && flieChildren.length;
            let rl = realFileChildren.length;
            let relationArr = item.relationArr;
            if (fl == 0 && rl > 0) {
                relationArr.type = 1;
                relationArr.exclude.push(item.path + "**.*");
                return;
            }
            if (rl <= 0) {
                return;
            }
            if (fl == rl) {
                relationArr.type = 1;
                relationArr.include.push(item.path + "**.*");
            } else {
                if (fl * 2 > rl) {
                    relationArr.type = 1;
                    relationArr.include.push(item.path + "**.*");
                    for (let j = 0, length = realFileChildren.length; j < length; j++) {
                        let excludeStr = realFileChildren[j];
                        if (flieChildren.indexOf(excludeStr) < 0) {
                            relationArr.exclude.push(excludeStr);
                        }
                    }
                } else {
                    relationArr.type = 2;
                    relationArr.include = relationArr.include.concat(flieChildren);
                }
            }
        }

        private async doFolder(rootPath: string, item: FormatData) {
            //子文件夹处理
            let folderChildren = item.folderChildren;
            let fll = folderChildren.length;
            let relationArr = item.relationArr;

            let realFolderChildren = await this.getPathFile(item.path, "*/", { cwd: rootPath });
            let rll = realFolderChildren.length;
            if (fll == 0 && rll > 0) {
                return;
            }
            if (rll <= 0) {
                return;
            }
            let childrenFolderPath: string[] = [];
            //判断子文件夹是否是全包含
            let flag = 0;
            for (let i = 0, length = fll; i < length; i++) {
                let childFolder = folderChildren[i];
                if (!childFolder) {
                    continue;
                }
                childrenFolderPath.push(childFolder.path);
                let relation = childFolder.relationArr.type;
                if (relation != 1) {
                    continue;
                }
                flag++;
            }
            //子文件夹的文件 或者 子文件 不全是*.* 或者*.*+exclude情况 
            if (flag != fll || relationArr.type == 2) {
                for (let i = 0, length = fll; i < length; i++) {
                    let childFolder = folderChildren[i];
                    if (!childFolder) {
                        continue;
                    }
                    relationArr.type = 2;
                    relationArr.include = relationArr.include.concat(childFolder.relationArr.include);
                    relationArr.exclude = relationArr.exclude.concat(childFolder.relationArr.exclude);
                }
                return;
            }
            if (fll == rll) {
                relationArr.type = 1;
                relationArr.include = [item.path + "**"];

                for (let i = 0, length = fll; i < length; i++) {
                    let childFolder = folderChildren[i];
                    if (!childFolder) {
                        continue;
                    }
                    relationArr.exclude = relationArr.exclude.concat(childFolder.relationArr.exclude);
                }
            } else {
                if (fll * 2 > rll) {
                    relationArr.include = [item.path + "**"];
                    for (let i = 0, length = rll; i < length; i++) {
                        let excludeStr = realFolderChildren[i];
                        if (childrenFolderPath.indexOf(excludeStr) < 0) {
                            relationArr.exclude.push(excludeStr+ "**");
                        }
                    }
                    for (let i = 0, length = fll; i < length; i++) {
                        let childFolder = folderChildren[i];
                        if (!childFolder) {
                            continue;
                        }
                        relationArr.exclude = relationArr.exclude.concat(childFolder.relationArr.exclude);
                    }
                } else {
                    for (let i = 0, length = fll; i < length; i++) {
                        let childFolder = folderChildren[i];
                        if (!childFolder) {
                            continue;
                        }
                        relationArr.type = 2;
                        relationArr.include = relationArr.include.concat(childFolder.relationArr.include);
                        relationArr.exclude = relationArr.exclude.concat(childFolder.relationArr.exclude);
                    }
                }
            }
        }

        private async getPathFile(path: string, subPath: string, option: glob.IOptions): Promise<string[]> {
            return new Promise<string[]>((resolve, rejects) => {
                glob(path + subPath, option, (err: Error | null, match: string[]) => {
                    if (err) {
                        rejects('glob error: ' + err);
                    } else {
                        resolve(match);
                    }
                });
            });
        }
    }
}